package com.talkyun.openx.ocean.proxy;

import com.talkyun.ocean.RegistryClient;
import com.talkyun.openx.RestfulSpringFactory;
import com.talkyun.openx.client.AbstractProxy;
import com.talkyun.openx.ocean.RegistryManager;

import java.lang.reflect.Proxy;

import static java.lang.Thread.currentThread;

public class RegistryableProxyFactory extends RestfulSpringFactory {
    private RegistryManager rm = RegistryManager.get();

    private String id;

    public void setId(String id) {
        this.id = id;
    }

    @Override
    public Object getObject() throws Exception {
        String url = super.getUrl();
        if (super.isBlank(url)) {
            return this.getRegistryableService();
        }
        return super.getObject();
    }

    private Object getRegistryableService() {
        RegistryClient client = rm.getRegistryClient();
        Class<?> api = super.getInterface();
        AbstractProxy proxy = new RegistryableRandomProxy(client, api);
        ClassLoader loader = currentThread().getContextClassLoader();
        return Proxy.newProxyInstance(loader, new Class[]{api}, proxy);
    }
}